package com.example.demo;


import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.window.SplashScreenView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.view.WindowCompat;

import com.example.demo.splash.MainSplashScreen;

import java.util.Map;

import io.flutter.Log;
import io.flutter.embedding.android.DrawableSplashScreen;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.android.SplashScreen;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity implements MethodChannel.MethodCallHandler {

    private static final String CHANNEL = "plugins.io/app";
    private MethodChannel methodChannel;

    @Nullable
    @Override
    public SplashScreen provideSplashScreen() {
        Drawable manifestSplashDrawable = getSplashScreenFromManifest();
        if (manifestSplashDrawable != null) {
            return new MainSplashScreen(manifestSplashDrawable);
        } else {
            return null;
        }
    }

    @Nullable
    private Drawable getSplashScreenFromManifest() {
        try {
            Bundle metaData = getMetaData();
            int splashScreenId = metaData != null ? metaData.getInt("io.flutter.embedding.android.SplashScreenDrawable") : 0;
            return splashScreenId != 0
                    ? ResourcesCompat.getDrawable(getResources(), splashScreenId, getTheme())
                    : null;
        } catch (Resources.NotFoundException e) {
            Log.e("MainActivity", "Splash screen not found. Ensure the drawable exists and that it's valid.");
            throw e;
        } catch (PackageManager.NameNotFoundException e) {
            // This is never expected to happen.
            return null;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            getSplashScreen()
                    .setOnExitAnimationListener(
                            (SplashScreenView splashScreenView) -> {
                                splashScreenView.remove();
                            });
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        initAppChannel(flutterEngine);
    }

    @Override
    public void cleanUpFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.cleanUpFlutterEngine(flutterEngine);
        clearAppChannel();
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        final Map<String, Object> args = call.arguments();
        switch (call.method) {
            case "getImageResource": {
                if (!args.containsKey("imageName") || !args.containsKey("defType")) {
                    result.error("-1", "please check your params value", null);
                    return;
                }
                byte[] resourceByte = MainChannelImpl.getAppResourceImage(
                        getResources(),
                        getResources().getIdentifier((String) args.get("imageName"), (String) args.get("defType"), getPackageName()));
                result.success(resourceByte);
            }
            break;
            default: {
                result.notImplemented();
            }
            break;
        }
    }

    private void initAppChannel(@NonNull FlutterEngine flutterEngine) {
        methodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL);
        methodChannel.setMethodCallHandler(this);
    }

    private void clearAppChannel() {
        methodChannel.setMethodCallHandler(null);
        methodChannel = null;
    }
}
